//
//  ETH+Account.swift
//  XHWalletUtils
//
//  Created by xinph on 2020/5/16.
//  Copyright © 2020 xinph. All rights reserved.
//

import Foundation

extension ETH: AccountProtocol {
    public static func createAccountByPrivate(_ password: String, name: String) -> coswift.Promise<WalletType> {
        let promise = coswift.Promise<WalletType>()
        
        let password = password // We recommend here and everywhere to use the password set by the user.
        let keystore: EthereumKeystoreV3
        do {
            keystore = try EthereumKeystoreV3(password: password)!
        } catch {
            promise.reject(error: XHError(createWalletFailure))
            return promise
        }
        let keyData = try! JSONEncoder().encode(keystore.keystoreParams)
        let address = keystore.addresses!.first!.address
        let account = Account(name, address: address, coin: 60)
        let wallet = ETH(keystore: keyData, path: CoinBIP44.defaultETHPath,isHD: false, privateKey: nil, publicKey: nil)
        Manager.IO.writeWallet(account, wallet: wallet)
        _ = wallet.generateWeb3()
        promise.fulfill(value: wallet)
     
        return promise
    }
    
    public static func importAccountByPrivate(_ password: String, name: String, private: String) -> coswift.Promise<WalletType> {
        let promise = coswift.Promise<WalletType>()

        guard !`private`.isEmpty else {
            promise.reject(error: XHError(privateKeyError))
            return promise
        }
        let formattedKey = `private`.trimmingCharacters(in: .whitespacesAndNewlines)
        let dataKey = Data.fromHex(formattedKey)!
        let keystore: EthereumKeystoreV3
        do {
            keystore = try EthereumKeystoreV3(privateKey: dataKey, password: password)!
            let keyData = try! JSONEncoder().encode(keystore.keystoreParams)
            let address = keystore.addresses!.first!.address
            let account = Account(name, address: address, coin: 60)
            let wallet = ETH(keystore: keyData, path: CoinBIP44.defaultETHPath,isHD: false, privateKey: nil, publicKey: nil)
            Manager.IO.writeWallet(account, wallet: wallet)
            _ = wallet.generateWeb3()
            promise.fulfill(value: wallet)
            return promise
        } catch {
            promise.reject(error: XHError(privateKeyError))
       
            return promise
        }
    }
}
